package com.limeng.hibernate;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ModelUtil {
	private static Logger log = Logger.getLogger(ModelUtil.class.getName());
	private static final SessionFactory sessionFactory;

	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable e) {
			log.log(Level.SEVERE, "Could not create Hibernate SessionFactory: " + e.getCause());
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Session getSession() {
		return getSessionFactory().getCurrentSession();
	}

	public static Session newSession() {
		return getSessionFactory().openSession();
	}

	public static Session ensureUsableSession(Session session) {
		if (session == null) {
			session = ModelUtil.getSession();
		}
		session.beginTransaction();
		return session;
	}

	public static void rollback() {
		Session session = ModelUtil.getSession();
		Transaction transaction = session.getTransaction();
		if (transaction.isActive()) {
			transaction.rollback();
		}
	}

}
